package cn.edu.scau.dormitory_management_system.controller;

import cn.edu.scau.dormitory_management_system.entity.dto.ReportDTO;
import cn.edu.scau.dormitory_management_system.service.ExportService;
import cn.edu.scau.dormitory_management_system.service.ImportService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author djc
 * @date 2021/8/6
 * @time 9:35
 */
@RestController
@RequestMapping("/admin/report")
public class ReportController {
    @Autowired
    private ExportService exportService;

    @Autowired
    private ImportService importService;

    /**
     * @param multipartFile 文件
     * @param option 导入类型选择
     * @return json数据
     */
    @PostMapping("/import")
    public Object importFile(@RequestParam(value = "file", required = false) MultipartFile multipartFile,
                             int option) {
        JSONObject object = new JSONObject();

        ReportDTO reportDTO = importService.importFile(multipartFile, option);
        if(reportDTO == null) {
            object.put("code", 0);
            object.put("msg", "导入失败");
        }else {
            object.put("code", 200);
            object.put("importInfo", reportDTO);
        }

        return object;
    }

    @PostMapping("/export")
    public void exports(@RequestBody List<String> value,
                       HttpServletResponse response) {
        int option = Integer.parseInt(value.get(0));
        exportService.creteExcelFile(option, value.subList(1, value.size()), response);
    }

    @PostMapping("/export/bill/build")
    public void exportFiles(@RequestBody List<Integer> ids,
                           HttpServletResponse response) {
        exportService.createExcelFile("dorm_build_id", ids,
                "bill_time", 0, response);
    }

    @PostMapping("/export/bill/dorm")
    public void export(@RequestBody List<String> names,
                           HttpServletResponse response) {
        exportService.createExcelFile("dorm_name", names,
                "bill_time", 0, response);
    }
}
